package offer;

public class DeleteNode {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(4);
        listNode.next = new ListNode(5);
        listNode.next.next = new ListNode(1);
        listNode.next.next.next = new ListNode(9);
        ListNode res = deleteNode(listNode, 5);
    }

    public static ListNode deleteNode(ListNode head, int val) {
        ListNode curr = head;
        ListNode pre = null;
        while (curr != null) {
            if (val == curr.val) {
                if (pre == null) {
                    head = curr.next;
                } else {
                    pre.next = curr.next;
                }
                curr = null;
                return head;
            }
            pre = curr;
            curr = curr.next;

        }
        return head;
    }
}
